from .data.factor_look import FactorLooker
import time
from trade.broker.base import BrokerBase
from trade.strategy import BaseStrategy


class BackTestModel:
    broker: BrokerBase
    strategy: BaseStrategy
    looker: FactorLooker

    def __init__(self, broker, strategy, looker):
        strategy.set_broker_model(broker)
        self.broker = broker
        self.strategy = strategy
        self.looker = looker

    def run_sliding(
        self, is_sim: True, start: int = None, end: int = None, datablk: int = 1000
    ):
        if is_sim:
            self.broker.reset()
            slider = self.looker.db_for_factors(
                start, end, self.strategy.preloads, datablk
            )
        else:
            slider = self.looker.online_for_factors(
                time.time() * 1000, self.strategy.preloads
            )
        try:
            for _ in slider:
                if (unimrr := self.broker.get_unimrr()) < 2:
                    print(f"爆仓了， {unimrr}")
                    self.broker.force_clear_positions()
                    self.broker.force_clear_balances()
                    self.broker.force_clear_positions()
                    self.broker.force_clear_balances()
                    raise Exception(f"爆仓了，赶紧强平")

                self.strategy.apply()
                print(
                    f"{self.broker.get_cur_time()} 当前比特币：{self.broker.get_data('BTC/USDT', 'close', 0)}， "
                    f"当前资产总额： {self.broker.get_account_value()}, 当前unimrr: {unimrr}"
                )
        finally:
            self.strategy.after_all()
